package systemController

import (
	"context"
	"encoding/json"
	"net/http"
	"strconv"
	"wisdomCoach/global"
	"wisdomCoach/model"
	"wisdomCoach/model/request"
	"wisdomCoach/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 获取用户详情带权限
func GetInfo(cxt *gin.Context) {
	var (
		user model.User
	)
	userId := cxt.GetInt64("userId")
	if err := global.DB.Preload("Dept").Preload("Roles", func(db *gorm.DB) *gorm.DB {
		return db.Preload("Menus")
	}).Where("user_id = ?", userId).First(&user).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	var roles []string
	var permissions []string
	for i := 0; i < len(user.Roles); i++ {
		roles = append(roles, user.Roles[i].RoleKey)
		for j := 0; j < len(user.Roles[i].Menus); j++ {
			permissions = append(permissions, user.Roles[i].Menus[j].Perms)
		}
	}
	permissions = utils.UniqueStringSlice(permissions)
	ctx := context.Background()
	str := strconv.FormatInt(userId, 10)
	userIdStr := "user:" + str
	permissionsStr := "permissions:" + str
	rolesStr := "roles:" + str
	userJson, _ := json.Marshal(user)
	permissionsJson, _ := json.Marshal(permissions)
	rolesJson, _ := json.Marshal(roles)
	global.REDIS.Set(ctx, userIdStr, userJson, 0).Result()
	global.REDIS.Set(ctx, permissionsStr, permissionsJson, 0).Result()
	global.REDIS.Set(ctx, rolesStr, rolesJson, 0).Result()

	cxt.JSON(http.StatusOK, gin.H{
		"code":        200,
		"msg":         "操作成功",
		"roles":       roles,
		"user":        user,
		"permissions": permissions,
	})
}

// 获取部门树形数据
func DeptTree(cxt *gin.Context) {
	dept := make([]*model.Dept, 0)
	if err := global.DB.Find(&dept).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
	}
	deptTree := utils.TreeDept(dept)

	cxt.JSON(http.StatusOK, gin.H{
		"code":    200,
		"data":    deptTree,
		"message": "操作成功",
	})
}

// 获取用户列表
func GetUserList(cxt *gin.Context) {
	var (
		userList   []*model.User
		request    request.RequestUserList
		totalCount int64
	)

	if err := cxt.ShouldBindQuery(&request); err != nil {
		cxt.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	// params := map[string]interface{}{
	// 	"create_time": "",
	// }
	// fmt.Println(params)
	DB := global.DB
	DB.Table("sys_user")

	if request.UserName != "" {
		DB = DB.Where("user_name like ?", "%"+request.UserName+"%")
	}
	if request.Phonenumber != "" {
		DB = DB.Where("phonenumber like ?", "%"+request.Phonenumber+"%")
	}
	if request.Status != "" {
		DB = DB.Where("status = ?", request.Status)
	}
	if request.DeptId != 0 {
		DB = DB.Where("dept_id = ?", request.DeptId)
	}

	if request.Params != nil {
		DB = DB.Where("create_time BETWEEN ? AND ?", request.Params.BeginTime, request.Params.EndTime)
	}
	offset := (request.PageNum - 1) * request.PageSize
	// 打印查询条件，用于调试
	if err := DB.Preload("Dept").Offset(offset).Limit(request.PageSize).Find(&userList).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	if err := DB.Model(&model.User{}).Count(&totalCount).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	cxt.JSON(http.StatusOK, gin.H{
		"code":  200,
		"rows":  userList,
		"msg":   "查询成功",
		"total": totalCount,
	})
}

// 根据ID获取user
func GetUser(cxt *gin.Context) {
	userID := cxt.Param("id")
	var (
		postList []*model.Post
		roleList []*model.Role
		user     model.User
	)

	if err := global.DB.Find(&postList).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	if err := global.DB.Find(&roleList).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	if err := global.DB.Preload("Dept").Preload("Roles").Preload("Posts").Where("user_id = ?", userID).First(&user).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	roleIds := make([]int64, 0)
	for i := 0; i < len(user.Roles); i++ {
		roleIds = append(roleIds, user.Roles[i].RoleID)
	}
	postIds := make([]int64, 0)
	for i := 0; i < len(user.Posts); i++ {
		postIds = append(postIds, user.Posts[i].PostId)
	}
	cxt.JSON(http.StatusOK, gin.H{
		"code":    200,
		"msg":     "操作成功",
		"posts":   postList,
		"roles":   roleList,
		"data":    user,
		"postIds": postIds,
		"roleIds": roleIds,
	})
}

// 获取职位和角色列表
func GetPostsAndRoles(cxt *gin.Context) {
	var (
		postList []*model.Post
		roleList []*model.Role
	)

	if err := global.DB.Find(&postList).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}
	if err := global.DB.Find(&roleList).Error; err != nil {
		cxt.JSON(http.StatusInternalServerError, gin.H{
			"error": "服务器异常",
		})
		return
	}

	cxt.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "操作成功",
		"posts": postList,
		"roles": roleList,
	})
}

func AddUser(cxt *gin.Context) {
	tx := global.DB.Begin()

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	var (
		request request.RequestUser
	)
	if err := cxt.ShouldBindJSON(&request); err != nil {
		cxt.JSON(http.StatusOK, gin.H{
			"code":  500,
			"error": err,
		})
		return
	}

	user := model.User{
		DeptId:      request.DeptId,
		NickName:    request.NickName,
		UserName:    request.UserName,
		Sex:         request.Sex,
		Phonenumber: request.Phonenumber,
		Email:       request.Email,

		Common: model.Common{
			Remark:   request.Remark,
			Status:   request.Status,
			CreateBy: cxt.GetString("userName"),
		},
	}

	password, err := utils.EncryptPassword(request.Password)
	if err != nil {
		cxt.JSON(http.StatusOK, gin.H{
			"code":  500,
			"error": err,
		})
		return
	}
	user.Password = password

	if err := tx.Create(&user).Error; err != nil {
		tx.Rollback()
		cxt.JSON(http.StatusOK, gin.H{
			"code":  500,
			"error": err,
		})
		return
	}
	for _, v := range *request.RoleIds {
		userRole := model.UserRole{
			RoleId: v,
			UserId: user.UserId,
		}
		if err := tx.Create(&userRole).Error; err != nil {
			tx.Rollback()
			cxt.JSON(http.StatusOK, gin.H{
				"code":  500,
				"error": err,
			})
			return
		}
	}
	for _, v := range *request.PostIds {
		userPost := model.UserPost{
			PostId: v,
			UserId: user.UserId,
		}
		if err := tx.Create(&userPost).Error; err != nil {
			tx.Rollback()
			cxt.JSON(http.StatusOK, gin.H{
				"code":  500,
				"error": err,
			})
			return
		}
	}
	// 提交事务
	if err := tx.Commit().Error; err != nil {
		cxt.JSON(http.StatusOK, gin.H{
			"code":  500,
			"error": err,
		})
		return
	}
	cxt.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
	})
}

func EditUser(cxt *gin.Context) {
 
}
